package cn.itsource.web.interceptor;

import cn.itsource.domain.Employee;
import cn.itsource.domain.Permission;
import cn.itsource.mapper.PermissionMapper;
import cn.itsource.web.controller.LoginController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**--------------------------------------------------------
权限检查
 --------------------------------------------------------**/
@Component
@Slf4j
public class PermissionCheckInterceptor implements HandlerInterceptor{

    @Autowired
    private PermissionMapper permissionMapper ;

    /**--------------------------------------------------------
     步骤说明：
     1.获取登录用户，拿到权限
     2.获取访问的资源，加载需要的权限
     3.判断用户的权限包不包含资源需要的权限
     HandlerMethod met = (HandlerMethod)handler ;
     --------------------------------------------------------**/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {


        //1.获取登录用户，拿到权限
        Employee employee = (Employee) request.getSession().getAttribute(LoginController.EMPLOYEE_IN_SESSION);
        if(employee == null){
            response.sendRedirect("/login.html");
            return false;
        }

        if(employee.isAdmin())return true;

        //用户的权限
        List<Permission> permissions = employee.getPermissions();

        //2.获取访问的资源（URL），加载需要的权限
        String requestURI = request.getRequestURI();
        log.info("登录检查，请求的URI：{}",requestURI );
        Permission permission = permissionMapper.selectByUrl(requestURI);

        //如果URL没有权限，就是不需要权限就能访问
        if( null == permission){
            return true;
        }

        //3.判断用户的权限包不包含资源需要的权限
        if(permissions.size() == 0){
            return toNoPermission(response,handler);
        }

        for(Permission p : permissions){
            //如果用户包含权限，放行
            if(p.getId().equals(permission.getId())){
                return true;
            }
        };

        //没权限
        return toNoPermission(response,handler);

    }

    private boolean toNoPermission(HttpServletResponse response,Object handler){
        try {

            HandlerMethod met = (HandlerMethod)handler ;
            //如果方法上有 ResponseBody ，代表要返回JSON，以JSON格式返回没有权限
            ResponseBody methodAnnotation = met.getMethodAnnotation(ResponseBody.class);
            if(methodAnnotation != null){
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print("{success:false,code:401,message:'没有权限'}");
            }else{
                //否则是平台的请求，直接重定向到没权限页面
                response.sendRedirect("/nopermission.html");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
